package com.bcxj.servicepay.controller;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.app.models.AlipayTradeAppPayResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.bcxj.servicepay.service.AlipayService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: AlipayController
 * Package: com.bcxj.servicepay.controller
 * Description:
 *
 * @Author BCXJ
 * @Create 2024/11/24 18:06
 * @Version 1.0
 * @Since 1.0
 */
@RestController
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    @GetMapping("pay")
    public String pay(String subject, String outTradeNo, String totalAmount) {
        AlipayTradePagePayResponse response;
        try {
            response = Factory.Payment.Page().pay(subject, outTradeNo, totalAmount, "");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response.getBody();
    }


    @PostMapping("notify")
    public String notify(HttpServletRequest request) throws Exception {
        String tradeStatus = request.getParameter("trade_status");

        if(tradeStatus.trim().equals("TRADE_SUCCESS")) {
            HashMap<String, String> map = new HashMap<>();
            Map<String, String[]> parameterMap = request.getParameterMap();
            parameterMap.forEach((key, value) -> {
                map.put(key, parameterMap.get(key)[0]);
            });

            if(Factory.Payment.Common().verifyNotify(map)) {
                System.out.println("通过支付宝的验证");
            }
            // 获取订单的id
            String orderId = map.get("out_trade_no");
            // 回调service-order 的订单完成功能
            alipayService.pay(orderId);

        }else {
            System.out.println("支付宝验证不通过");
        }
        return "success";
    }
}
